import axios from 'axios';
const baseUrl = process.env.VUE_REQUEST_BASE_URL; // 方便后面修改能够直接集成springboot
//  配置请求头
const headers = { 'Content-Type': 'application/json' },
  fetch = (options) => {
    const {
      method = 'get',
      params,
      url
    } = options;
    // 对象解构
    switch (method.toLowerCase()) {
      case 'get':
        return axios({
          baseURL: baseUrl,
          headers,
          url,
          method: 'get',
          params,
          timeout: 10000,
          withCredentials: true
        });
      case 'post':
        return axios({
          headers,
          baseURL: baseUrl,
          url,
          method: 'post',
          data: JSON.stringify(params),
          timeout: 10000,
          withCredentials: true
        });
      default:
        return axios(options);
    }
  };

export default function request(options) {
  return fetch(options).then((response) => {
    // console.log('成功调用方法时...', response);
    if (response.status === 200) {
      return response;
    }
    const { status } = response;
    let data = response.data;
    data = typeof data === 'object' ? data : { stringData: data };
    return {
      success: true,
      statusCode: status,
      data
    };
  }).catch((error) => {
    let msg;
    let statusCode;
    // 访问超时（5s）
    if (!error.response) {
      statusCode = 600;
      msg = '网络异常,请稍后再试！';
      return { success: false, statusCode, message: msg };
    }
    const { response } = error;
    if (response && response instanceof Object) {
      const { data, statusText } = response;
      statusCode = response.status;
      msg = data.message || statusText;
      return { success: false, statusCode, message: msg };
    }
  });
}
